<script setup>
import { ref, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import LeaveTable from '@/components/leave/LeaveTable.vue'
import StatusTag from '@/components/common/StatusTag.vue'
import FloatingBackButton from '@/components/common/FloatingBackButton.vue'
import LogoutButton from '@/components/common/LogoutButton.vue'
import { getApprovals } from '@/api'

const router = useRouter()
const openApproval = (id) => router.push(`/teacher/approvals/${id}`)

// 数据
const approvals = ref([])
const loading = ref(false)
const filterStatus = ref('pending') // pending, approved, rejected, all

// 获取待审批列表
const fetchApprovals = async () => {
  loading.value = true
  try {
    const response = await getApprovals({ page: 1, pageSize: 100, status: filterStatus.value })
    if (response.code === 0 && response.data) {
      const rows = response.data.rows || []
      approvals.value = rows.map((item) => ({
        id: item.id,
        typeLabel: item.type === 'sick' ? '病假' : item.type === 'personal' ? '事假' : '其他',
        timeRange: `${formatDateTime(item.start_at)} ~ ${formatDateTime(item.end_at)}`,
        hours: item.hours,
        status: item.status,
        studentName: item.student_name || '未知',
      }))
    }
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

onMounted(() => {
  fetchApprovals()
})

// 每次页面激活时刷新数据
onActivated(() => {
  fetchApprovals()
})
</script>

<template>
  <div class="page">
    <div class="container">
      <div class="header">
        <h2>审批管理</h2>
      </div>

      <!-- 状态筛选 -->
      <div class="status-tabs">
        <button
          v-for="status in ['pending', 'approved', 'rejected', 'all']"
          :key="status"
          :class="['tab', filterStatus === status ? 'active' : '']"
          @click="filterStatus = status; fetchApprovals()"
        >
          {{ status === 'pending' ? '待审批' : status === 'approved' ? '已通过' : status === 'rejected' ? '已驳回' : '全部' }}
        </button>
      </div>

      <div v-if="loading" class="loading-text">加载中...</div>
      <LeaveTable v-else :items="approvals" role="teacher">
        <template #status="{ status }">
          <StatusTag :status="status" size="sm" />
        </template>
        <template #actions="{ row }">
          <button v-if="filterStatus === 'pending'" class="link" @click="openApproval(row.id)">审批</button>
          <button v-else class="link" @click="openApproval(row.id)">查看</button>
        </template>
      </LeaveTable>
    </div>
    <FloatingBackButton />
    <LogoutButton />
  </div>
</template>

<style scoped>
.page {
  position: fixed;
  inset: 0;
  padding: 32px 24px;
  overflow: auto;
  background:
    radial-gradient(circle at 20% 10%, rgba(255, 105, 0, 0.04) 0%, transparent 40%),
    radial-gradient(circle at 80% 90%, rgba(255, 105, 0, 0.04) 0%, transparent 40%);
}
.container {
  width: 100%;
  max-width: 1120px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header h2 {
  font-size: 22px;
  color: #1d1d1f;
}
.status-tabs {
  display: flex;
  gap: 12px;
  padding: 12px 0;
}
.tab {
  padding: 8px 16px;
  border: 1px solid #e5e7eb;
  background: #fff;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  transition: all 0.3s ease;
}
.tab:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
}
.tab.active {
  background: var(--color-primary);
  color: #fff;
  border-color: var(--color-primary);
}
.btn.primary {
  background: var(--color-primary);
  color: #fff;
  border: none;
  padding: 10px 14px;
  border-radius: 8px;
  font-weight: 700;
  cursor: pointer;
}
.btn.ghost {
  background: #fff;
  border: 1px solid #e5e7eb;
  padding: 10px 14px;
  border-radius: 8px;
  cursor: pointer;
}
.link {
  background: transparent;
  border: none;
  color: var(--color-primary);
  cursor: pointer;
  font-weight: 600;
}
.loading-text {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}
</style>
